<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
	<head>
		<meta charset="utf-8">
		<title>播放界面</title>
		<link href="/user/css/bootstrap.min.css" rel="stylesheet" />
		
		<link rel="stylesheet" href="http://at.alicdn.com/t/font_2989423_wcg2wl0kqig.css" />
<!--		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">-->
<!--		<link rel="stylesheet" href="/base/bootstrap-icons.css">-->
		<link rel="stylesheet" type="text/css" href="/user/css/index.css" />
		<link rel="stylesheet" type="text/css" href="/user/css/play.css" />
		<link rel="stylesheet" type="text/css" href="/user/css/sleep.css"/>
		<link rel="stylesheet" href="/user/css/index1.css">
		<link rel="stylesheet" href="/user/css/player.css">
		<link rel="stylesheet" href="/user/css/ping.css">
		<script src="/user/js/jquery.js"></script>
		<script src="/user/js/Popper.js"></script>
		
		<script src="/user/js/bootstrap.min.js"></script>
		<link rel="stylesheet" href="../../../../../alert/main.css">
	</head>
	<body>
		<div class="container">
			<nav class="navbar navbar-expand-md navbar-light slep">
				<div id="span1">
					<img class="rounded-circle" src="/img/logoindex.jpg">
					<span>星语乐章</span>
				</div>
				<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#myNav">
					<span class="navbar-toggler-icon">

					</span>
				</button>
				<div class="collapse navbar-collapse" id="myNav">
					<ul class="navbar-nav" style="list-style: none;">
						<li class="nav-item active">
							<a class="nav-link" href="/user/userIndex">首页</a>
						</li>
						<li class="nav-item " th:if="${session.user==null}">
							<a class="nav-link" href="/user/userLoginIndex">登录</a>
						</li>
						<li class="nav-item " th:if="${session.user!=null}">
							<a class="nav-link" href="#" th:text="${session.user.getUserName()}" style="color: red!important;"></a>
						</li>
					</ul>
				</div>
			</nav>
		</div>
			<section class="music">
				<div class="list">
					<h2 th:text="${msg}"></h2>
					<div class="row"><span>序号</span><span>歌曲</span><span>歌手</span><span>专辑</span><span>时长</span></div>
					<div class="content" >
						<div class="row" name="wm" th:each="m:${list}">
							<span th:text="${mStat.index+1}"></span>
							<span th:text="${m.songName}"></span>
							<span th:text="${m.singerName}"></span>
							<span th:text="经典歌曲"></span>
							<span th:text="${m.songTime}"></span>
						</div>
					</div>
					<!-- content -->
				</div>
				<div class="cover">
					<img  alt="">
					<div class="content">
						<ul>
							<!-- <li>歌词搜索中...</li> -->
						</ul>
					</div>
				</div>
			</section>
			<!-- /主体 -->
			<!-- player -->
			<section class="player">
				<div class="play-bar">
					<div class="progress"></div>
					<div class="bar"></div>
				</div>
				<div class="play-box">
					<div class="info">
						<img  alt="">
						<span ></span>
						<i class="iconfont icon-aixin" onclick="love()" th:if="${session.user!=null}"></i>
<!--						<i class="bi bi-calendar2-minus" onclick="commentList()"></i>-->
						<i class="iconfont icon-fenxiang share" onclick="commentList()"></i>
					</div>
					<div class="play">
						<i class="iconfont icon-xiayishou" onclick="musicBefore()"></i>
						<div class="play-pause-box">
							<i class="iconfont icon-24gl-play"></i>
							<i class="iconfont icon-24gl-pause2" style="display:none;"></i>
						</div>
						<i class="iconfont icon-xiayishou" onclick="musicAfter()"></i>
					</div> 
					<div class="playbar-right">
						<span class="times"><span class="current">00:00</span>&nbsp;/&nbsp;<span class="duration">00:00</span></span>
						<div class="volume">
							<i class="iconfont icon-laba"></i>
							<div class="progress"></div>
							<div class="bar"></div>
						</div>
					</div>
				</div>
		
				<!-- music -->
				<video controls src="" style="display:none"></video>
			</section>
			
		<th:block th:if="${session.user!=null}">
			<input type="hidden" th:value="${session.user.id}" id="userId">
		</th:block>
			<script src="/user/js/nprogress.js"></script>



		<!--评论弹框-->
		<div class="mymodal"></div>
		<div class="popup-container">
			<div class="popup-header">
				评论查看
				<i class="fa fa-close close-btn"></i>
			</div>
			<div class="popup-body">
				<div class="comment-list">
					<ul id="commentList">
					</ul>
				</div>
			</div>
			<div class="popup-footer">
				<input type="text" placeholder="输入评论" id="userComment"/>
				<button onclick="userComment()">评论</button>
			</div>
		</div>
	</body>
	<script src="/user/js/ping.js"></script>
	<script th:inline="javascript">

		let wordList=[[${words}]];
		let workList=[[${list}]];
		console.log(workList)
		// # 音乐全局变量
		let musicI = 0
		let videoObj = document.querySelector('video')

		// # 点击音乐列表播放
		// 1 获取音乐列表
		let musicObjs = document.querySelectorAll('.music .list .content .row')

		// 2 遍历
		musicObjs.forEach((item, i) => { // item就是每一行音乐
			// 3 绑定点击事件
			// 4 事件处理函数中
			item.onclick = function() { // this item
				//添加功能-zsx-发送请求修改播放次数
				insNum(workList[i].id)
				//添加功能结束
				// 一、将当前索引保存全局的便于后面切换上下歌曲
				musicI = i
				// 二、左-播放动画效果（1-清空之前的动画改成索引，2-当前的增加动画）
				musicObjs.forEach((row, rowIndex) => {
					musicObjs[rowIndex].style.color = ''
					row.querySelector('span').innerText = rowIndex+1
				})
				musicObjs[i].style.color = 'rgb(6, 137, 212)'
				musicObjs[i].querySelector('span').innerHTML = `
            <i class="playing line1"></i>
            <i class="playing line2"></i>
            <i class="playing line3"></i>
        `
				// 三、右-切换图片
				let name = this.getAttribute('name')
				console.log("name:"+name)
				// 四、播放音乐 && 播放图标▶️
				// videoObj.src = `/user/music/${name}.mp3`
				videoObj.src = workList[i].song;
				document.querySelector('.music .cover img').src = `/user/img/img3/${name}.jpeg`
				document.querySelector('.music .cover img').src = workList[i].songImg
				videoObj.play()

				// document.querySelector('.player .info img').src = `/user/img/img3/${name}.jpeg`
				document.querySelector('.player .info img').src = workList[i].songImg
				document.querySelector('.player .info span').innerHTML = item.querySelector('span:nth-of-type(3)').innerHTML

				document.querySelector('.player .play-box .play .play-pause-box i:nth-of-type(1)').style.display = 'none'
				document.querySelector('.player .play-box .play .play-pause-box i:nth-of-type(2)').style.display = 'block'

				// 五、切换歌词（难）
				changeLrcFn()
			}
		})

		// # 切换歌词
		// # 同步歌词滚动
		function changeLrcFn()
		{
			let lrcs = wordList;
			console.log(lrcs)
			console.log(lrcs[musicI]);
			// 1 定义空数组存放 一个个对象  {time, content}
			// 2 遍历歌词提取time content push到空数组中
			let lrcFilter = lrcs[musicI].split('\n').map(item => {
				// [02:48.68]院子落叶跟我的思念厚厚一叠
				// [02:55.43]几句是非也无法将我的热情冷却
				// console.log(item);
				let temp = item.split(']')   //  ['[02:48.68', '院子落叶跟我的思念厚厚一叠]
				let timeArr = temp[0].replace('[', '').split(':')

				return {
					time: timeArr[0]*60+parseFloat(timeArr[1]),
					content: temp[1]
				}
			})




			// 因此：先清空
			document.querySelector('.music .cover ul').innerHTML = ''
			// 然后：再追加
			lrcFilter.forEach((item,i) => {
				let liObj = document.createElement('li')
				if (i===0) liObj.className = 'active'
				liObj.innerText = item.content
				document.querySelector('.music .cover ul').appendChild(liObj)
			})


			// 同步歌词
			videoObj.ontimeupdate = function() {
				// console.log('实时监控歌曲播放进度：', videoObj.currentTime)
				// console.log(lrcFilter);

				// 特殊：推荐用for循环 因为找到符合条件的就break退出 forEach不支持break
				// 一、找到播放进度索引
				let findIndex = 0
				for (let i=lrcFilter.length-1; i>=0; i--)
				{

					if ((videoObj.currentTime+.5) >= lrcFilter[i].time)
					{
						findIndex = i
						break
					}
				}
				// console.log(findIndex);
				// 二、高亮歌词 & 滚动到高亮位置
				if (lrcFilter[findIndex].content)
				{
					// 高亮歌词
					document.querySelector('.music .cover ul li.active').className = ''
					document.querySelector(`.music .cover ul li:nth-of-type(${findIndex+1})`).className = 'active'
					// 滚动到高亮位置
					document.querySelector(`.music .cover ul`).style.marginTop = -(findIndex)*40 + 'px'
				}

				// 同步播放进度
				let m = Math.floor(videoObj.currentTime/60)
				let s = parseInt(videoObj.currentTime - m*60)
				document.querySelector('.player .current').innerText = `${String(m).padStart(2,0)}:${String(s).padStart(2,0)}`

				if (videoObj.duration)
				{
					let m = Math.floor(videoObj.duration/60)
					let s = Math.floor(videoObj.duration - m*60)
					let totalPlay = String(m).padStart(2, 0) + ':' + String(s).padStart(2, 0)
					document.querySelector('.player .duration').innerText = totalPlay

					// 同步进度条
					let w = window.innerWidth || document.documentElement.clientWidth
					document.querySelector('.player .play-bar .progress').style.width =  w / (videoObj.duration / videoObj.currentTime) + 'px'
					document.querySelector('.player .play-bar .bar').style.left =  w / (videoObj.duration / videoObj.currentTime) + 'px'
				}
			}
		}


		// # 播放按钮
		let player = document.querySelector('.player')

		player.querySelector('.play-pause-box').onclick = function() {
			console.log(videoObj.paused)

			if (videoObj.paused)
			{ // 已暂停没播放

				document.querySelector('.player .play-box .play .play-pause-box i:nth-of-type(1)').style.display = 'none'
				document.querySelector('.player .play-box .play .play-pause-box i:nth-of-type(2)').style.display = 'block'

				videoObj.play()
			} else  {
				// 未暂停
				document.querySelector('.player .play-box .play .play-pause-box i:nth-of-type(1)').style.display = 'block'
				document.querySelector('.player .play-box .play .play-pause-box i:nth-of-type(2)').style.display = 'none'

				videoObj.pause()
			}
		}

		// # 进度条拖拽
		// 一、给拖拽按钮绑定点击事件
		let barBtnObj = document.querySelector('.player .bar')
		// 二、事件处理函数中
		barBtnObj.onmousedown = function() {
			// 2.1 给网页绑定鼠标移动事件 -> a-同步拖拽按钮，b-同步播放进度条，c-同步播放
			document.onmousemove = (evt) => {
				let e = evt || window.event
				let l = e.pageX  - this.offsetWidth/2
				if (l<0) l = 0
				let maxL = window.innerWidth || document.documentElement.clientWidth
				if (l>maxL) l=maxL
				this.style.left = l + 'px'
				document.querySelector('.player .progress').style.width = l+'px'



				videoObj.currentTime = videoObj.duration / (maxL/l)
			}

			// 2.2 给网页绑定鼠标松开事件 -> 取消拖拽
			document.onmouseup = function() {
				document.onmousemove = null
			}
		}

		// # 音频拖拽进度条
		let barvolumeObj = document.querySelector('.player .volume .bar')
		barvolumeObj.onmousedown = function()
		{
			document.onmousemove = (evt) => {
				let e = evt || window.event

				let w = window.innerWidth || document.documentElement.clientWidth
				let volume = document.querySelector('.player .volume')

				let l = e.pageX - volume.offsetLeft - this.offsetWidth/2
				if (l<0) l =0
				let maxL =  volume.offsetWidth
				if (l>maxL) l =maxL
				this.style.left = l + 'px'
				console.log(maxL, l);
				document.querySelector('.player .volume .progress').style.width =  l + 'px'
				// volume是音量值
				videoObj.volume = l/100
			}
			document.onmouseup = function() {
				document.onmousemove = null


			}
		}

		/**
		 * 自定义
		 * 上一首
		 * @作者 张绍鑫
		 */
		function musicBefore() {
			if (musicI>0){
				musicI--;
				// this item
				// 一、将当前索引保存全局的便于后面切换上下歌曲
				// 二、左-播放动画效果（1-清空之前的动画改成索引，2-当前的增加动画）
				musicObjs.forEach((row, rowIndex) => {
					musicObjs[rowIndex].style.color = ''
					row.querySelector('span').innerText = rowIndex+1
				})
				musicObjs[musicI].style.color = 'rgb(6, 137, 212)'
				musicObjs[musicI].querySelector('span').innerHTML = `
            <i class="playing line1"></i>
            <i class="playing line2"></i>
            <i class="playing line3"></i>
        `
				// 三、右-切换图片
				// 四、播放音乐 && 播放图标▶️
				// videoObj.src = `/user/music/${name}.mp3`
				videoObj.src = workList[musicI].song;
				document.querySelector('.music .cover img').src = workList[musicI].songImg
				videoObj.play()

				// document.querySelector('.player .info img').src = `/user/img/img3/${name}.jpeg`
				document.querySelector('.player .info img').src = workList[musicI].songImg
				document.querySelector('.player .info span').innerHTML = musicObjs[musicI].querySelector('span:nth-of-type(3)').innerHTML

				document.querySelector('.player .play-box .play .play-pause-box i:nth-of-type(1)').style.display = 'none'
				document.querySelector('.player .play-box .play .play-pause-box i:nth-of-type(2)').style.display = 'block'

				// 五、切换歌词（难）
				changeLrcFn()
			}


		}

		/**
		 * 自定义
		 * 下一首
		 * @作者 张绍鑫
		 */
		function musicAfter() {
			if (musicI<workList.length-1){
				musicI++;
				// this item
				// 一、将当前索引保存全局的便于后面切换上下歌曲
				// 二、左-播放动画效果（1-清空之前的动画改成索引，2-当前的增加动画）
				musicObjs.forEach((row, rowIndex) => {
					musicObjs[rowIndex].style.color = ''
					row.querySelector('span').innerText = rowIndex+1
				})
				musicObjs[musicI].style.color = 'rgb(6, 137, 212)'
				musicObjs[musicI].querySelector('span').innerHTML = `
            <i class="playing line1"></i>
            <i class="playing line2"></i>
            <i class="playing line3"></i>
        `
				// 三、右-切换图片
				// 四、播放音乐 && 播放图标▶️
				// videoObj.src = `/user/music/${name}.mp3`
				videoObj.src = workList[musicI].song;
				document.querySelector('.music .cover img').src = workList[musicI].songImg
				videoObj.play()

				// document.querySelector('.player .info img').src = `/user/img/img3/${name}.jpeg`
				document.querySelector('.player .info img').src = workList[musicI].songImg
				document.querySelector('.player .info span').innerHTML = musicObjs[musicI].querySelector('span:nth-of-type(3)').innerHTML

				document.querySelector('.player .play-box .play .play-pause-box i:nth-of-type(1)').style.display = 'none'
				document.querySelector('.player .play-box .play .play-pause-box i:nth-of-type(2)').style.display = 'block'

				// 五、切换歌词（难）
				changeLrcFn()
			}
		}


		/**
		 * 自定义
		 * 收藏
		 * @作者 张绍鑫
		 */
		function love() {
			let songId=workList[musicI].id;
			let userId=$('#userId').val();
			if (userId==null){
				alert("请先登录");
			}else {
				$.ajax({
					url:`/user/love/${userId}/${songId}`,
					type:'post',
					success:function (res) {
						alert(res);
					}
				})
			}
		}

		/**
		 * 自定义
		 * 播放歌曲，改变播放次数
		 * @作者 张绍鑫
		 */
		function insNum(songId) {
			$.ajax({
				url:'/listen/'+songId,
				type:'post',
			})
		}


		/**
		 * 自定义
		 * 请求评论数据
		 * 渲染到弹窗
		 * @作者 张绍鑫
		 */
		function commentList() {
			let songId = workList[musicI].id;
			$.ajax({
				url: `/user/commentList/${songId}`,
				type: 'get',
				success: function (res) {
					let list=res.data;
					let str=``;
					for (let i=0;i<list.length;i++){
						let obj=list[i];
						str+=`<li><span style="color: #8fdf82">${obj.user}</span>:${obj.comment}</li>`
					}
					$('#commentList').html(str);
					openPopup();
				}
			});
		}



		/**
		 * 自定义
		 * 用户评论
		 * 渲染到弹窗
		 * @作者 张绍鑫
		 */
		function userComment() {

			let songId=workList[musicI].id;
			let userId=$('#userId').val();
			let comment=$('#userComment').val()
			if (userId==null){
				alert("请先登录");
			}else {
				$.ajax({
					url:`/user/userComment`,
					type:'post',
					data:{userId: userId,songId:songId,comment:comment},
					success:function (res) {

						let list=res.data;
						let str=``;
						for (let i=0;i<list.length;i++){
							let obj=list[i];
							str+=`<li><span style="color: #8fdf82">${obj.user}</span>:${obj.comment}</li>`
						}
						$('#commentList').html(str);
					}
				})
			}
		}
	</script>
</html>
